package mMap;

/**
 * Created by
 * 项目名称：
 * 类描述：
 * 创建人：
 * 
 */

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Map工具类，存储List集合,在数据不多的时候内存缓存，数据多的时候猜数据库存储
 * 实现在应用中数据共享
 */
public class MapUtils {
    private Map<String, List<?>> map = new HashMap<>();

    private MapUtils() {
        map = new HashMap<>();
    }

    public Map<String, List<?>> getMap() {
        return map;
    }

    private static volatile MapUtils sInstance;

    public static MapUtils getInstance() {
        if (sInstance == null) {
            synchronized (MapUtils.class) {
                if (sInstance == null) {
                    sInstance = new MapUtils();
                }
            }
        }
        return sInstance;
    }

    public void putList(String key, List<?> list) {
        if (map.isEmpty()) {
            map = new HashMap<>();
        }
        if (list != null && list.size() > 0) {
            map.remove(key);
            map.put(checkKey(key), list);
        }
    }

    public List<?> getList(String key) {
        if (map.isEmpty()) {
            map = new HashMap<>();
        }
        if (map.containsKey(checkKey(key))) {
            return map.get(key);
        }
        //返回长度为0的，避免空指针
        return new ArrayList<>(0);
    }

    public void removeList(String key) {
        if (!map.isEmpty() && map.containsKey(checkKey(key))) {
            map.remove(key);
        }
    }

    public void removeAllList() {
        if (!map.isEmpty()) {
            map.clear();
        }
    }

    private String checkKey(String key) {
        if (key == null) {
            throw new NullPointerException("key must not be null");
        }
        return key;
    }
}
